package com.peas.platform.module.icims.base.auth.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.peas.platform.common.core.dto.ResponseDto;
import com.peas.platform.module.icims.base.auth.api.req.LoginReq;
import com.peas.platform.module.icims.base.auth.api.req.SaveRoleReq;
import com.peas.platform.module.icims.base.auth.api.req.SaveUserReq;
import com.peas.platform.module.icims.base.auth.api.req.UpdateUserPasswordReq;
import com.peas.platform.module.icims.base.auth.api.resp.LoginResp;
import com.peas.platform.module.icims.base.auth.api.resp.UserProfileResp;
import com.peas.platform.module.icims.base.auth.controller.vo.UserVo;
import com.peas.platform.module.icims.base.auth.dto.*;
import com.peas.platform.module.icims.base.auth.service.*;
import com.peas.platform.module.icims.base.sys.service.AttachmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "自定义接口-权限")
@RestController
@RequestMapping("/api/v1/custom")
@Slf4j
public class CustomLoginController {

    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;

    @Resource
    private UserService userService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;
    @Resource
    private RolePermissionService rolePermissionService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private AttachmentService attachmentService;
//    @Resource
//    @Lazy
//    private CaptchaService captchaService;

    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public ResponseDto<LoginResp> login(@RequestBody @Valid LoginReq vo) {
        assert response != null;
        HttpSession session = request.getSession();
        // Assert.equals(session.getAttribute("uuid"), vo.getUuid(), "页面错误，请刷新后重试");
        // Assert.equals(session.getAttribute("code"), vo.getCode(), "验证码错误");
        UserDto user = userService.login(vo.getUsername(), vo.getPassword(), request.getRemoteAddr());
        Assert.notNull(user, "账号或密码错误");
        LoginResp result = BeanUtil.copyProperties(user, LoginResp.class);
        result.setUserId(user.getId());
        return ResponseDto.getSuccessResponseDto(result);
    }

    /*
    private void validateCaptcha(String username, String code) {
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(code);
        ResponseModel response = captchaService.verification(captchaVO);
        if (!response.isSuccess()) {
            // AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new BaseException(Constants.DEFAULT_ERROR_CODE, response.getRepCode() + ":" + response.getRepMsg());
        }
    }
    */

    @ApiOperation(value = "修改密码")
    @PostMapping(value = "/updateUserPwd")
    public ResponseDto<Boolean> updateUserPwd(@RequestBody @Valid UpdateUserPasswordReq vo) {
        userService.reset(vo.getUserId(), vo.getPassword(), vo.getNewPassword());
        return ResponseDto.getSuccessResponseDto(true);
    }

    @ApiOperation(value = "根据用户ID获取用户及所属机构")
    @GetMapping(value = "/getUserProfile/{userId}")
    public ResponseDto<UserProfileResp> getUserProfile(@PathVariable("userId") Long userId) {
        UserDto user = userService.getById(userId);
        UserProfileResp profile = BeanUtil.copyProperties(user, UserProfileResp.class);
        Assert.notNull(user, "找不到用户");
        if (user.getOrganizationId() != null) {
            OrganizationDto org = organizationService.getById(user.getOrganizationId());
            profile.setDept(org);
        }
        List<UserRoleDto> userRoleDtos = userRoleService.listByField("userId", userId);
        if (CollUtil.isNotEmpty(userRoleDtos)) {
            List<PermissionDto> permissions = new ArrayList<>();
            List<RoleDto> roles = new ArrayList<>();
            for (UserRoleDto urd : userRoleDtos) {
                RoleDto r = roleService.getById(urd.getRoleId());
                roles.add(r);
                List<RolePermissionDto> rpds = rolePermissionService.listByField("roleId", r.getId());
                if (CollUtil.isNotEmpty(rpds)) {
                    List<Long> ids = new ArrayList<>();
                    for (RolePermissionDto rpd : rpds) {
                        if (!ids.contains(rpd.getPermissionId())) {
                            ids.add(rpd.getPermissionId());
                        }
                    }
                    permissions = permissionService.findListAndParentsByIds(ids);
                }
            }
            profile.setRoles(roles);
            profile.setPermissions(permissions);
        }
        return ResponseDto.getSuccessResponseDto(profile);
    }

    @ApiOperation(value = "修改用户个人信息")
    @PostMapping(value = "/updateProfile")
    public ResponseDto<Boolean> updateProfile(@RequestBody @Valid UserVo vo) {
        UserDto dto = BeanUtil.copyProperties(vo, UserDto.class);
        userService.updateById(dto);
        return ResponseDto.getSuccessResponseDto(true);
    }

    @SneakyThrows
    @ApiOperation(value = "根据用户ID获取签名图")
    @GetMapping(value = "/getSignImg/{userId}")
    public ResponseDto<String> getSignImg(@PathVariable("userId") Long userId) {
        UserDto user = userService.getById(userId);
        if (user.getSign() == null) {
            return ResponseDto.getSuccessResponseDto("");
        }
        try (InputStream is = attachmentService.getObject(user.getSign())) {
            return ResponseDto.getSuccessResponseDto(Base64.encode(is));
        }
    }

    @ApiOperation(value = "保存用户")
    @PostMapping(value = "/saveUser")
    public ResponseDto<Boolean> saveUser(@RequestBody @Valid SaveUserReq vo) {
        userService.saveUser(vo);
        return ResponseDto.getSuccessResponseDto(true);
    }

    @ApiOperation(value = "保存角色")
    @PostMapping(value = "/saveRole")
    public ResponseDto<Boolean> saveRole(@RequestBody @Valid SaveRoleReq vo) {
        roleService.saveRole(vo);
        return ResponseDto.getSuccessResponseDto(true);
    }

}
